package org.zhaya.sdk.processors;

import io.logz.sawmill.Doc;
import io.logz.sawmill.ProcessResult;
import io.logz.sawmill.Processor;
import io.logz.sawmill.annotations.ProcessorProvider;
import io.logz.sawmill.utilities.JsonUtils;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

import static java.util.Objects.requireNonNull;

@ProcessorProvider(type = "urldecode", factory = URLDecodeProcessor.Factory.class)
public class URLDecodeProcessor implements Processor {
    private final String field;
    private final String targetField;
    private final String charset;

    public URLDecodeProcessor(String field, String targetField, String charset) {
        this.field = requireNonNull(field, "field cannot be null");
        this.targetField = StringUtils.isBlank(targetField) ? field : targetField;
        this.charset = requireNonNull(charset, "charset cannot be null");
    }

    @Override
    public ProcessResult process(Doc doc) throws InterruptedException {
        if (!doc.hasField(field, String.class)) {
            return ProcessResult.failure(String
                    .format("failed to split field in path [%s], field is missing or not instance of String", field));
        }
        String encodedUrl = doc.getField(field);
        if (StringUtils.isNotBlank(encodedUrl)) {
            try {
                doc.addField(targetField, URLDecoder.decode(encodedUrl, charset));
            } catch (Exception e) {
                return ProcessResult.failure(String.format("Could not URL-decode value, field is [%s], msg=[%s]",
                        encodedUrl, e.getMessage()));
            }
        }
        return ProcessResult.success();
    }

    public static class Factory implements Processor.Factory {

        @Override
        public Processor create(Map<String, Object> config) {
            Configuration conf = JsonUtils.fromJsonMap(Configuration.class, config);
            return new URLDecodeProcessor(conf.getField(), conf.getTargetField(), conf.getCharset());
        }
    }

    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Configuration implements Processor.Configuration {
        private String field;
        private String targetField;
        private String charset = StandardCharsets.UTF_8.name();

    }
}